package com.szcinda.service.dto.orderFeeItem;

import com.szcinda.service.SnowFlakeFactory;
import com.szcinda.repository.OrderFeeItem;
import com.szcinda.repository.OrderFeeItemRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class OrderFeeItemServiceImpl implements OrderFeeItemService {

    private final OrderFeeItemRepository orderFeeItemRepository;
    private final SnowFlakeFactory snowFlakeFactory;

    public OrderFeeItemServiceImpl(OrderFeeItemRepository orderFeeItemRepository) {
        this.orderFeeItemRepository = orderFeeItemRepository;
        this.snowFlakeFactory = SnowFlakeFactory.getInstance();
    }


    @Override
    public void update(List<OrderFeeItemCreateDto> createDtos, String orderId) {
        orderFeeItemRepository.deleteAllByOrderId(orderId);
        if (createDtos != null && createDtos.size() > 0) {
            List<OrderFeeItem> feeItems = new ArrayList<>();
            createDtos.forEach(createDto -> {
                OrderFeeItem item = new OrderFeeItem();
                BeanUtils.copyProperties(createDto, item);
                item.setOrderId(orderId);
                item.setId(snowFlakeFactory.nextId("OF"));
                feeItems.add(item);
            });
            orderFeeItemRepository.save(feeItems);
        }
    }
}
